package com.avcdata.national.network;

import com.google.gson.Gson;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpRequest {

    static String client_id = "clientapp";
    static String client_secret = "123456";

    /**
     * 发送get请求
     *
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String doGet(String url, HashMap<String, String> maps,
                               String sessionId) throws ClientProtocolException, IOException {
        HttpGet httpGet = null;
        if (maps == null) {
            httpGet = new HttpGet(url);
        } else {
            String URL = url + "?";
            StringBuffer stringBuffer = new StringBuffer();

            for (Map.Entry<String, String> entry : maps.entrySet()) {
                stringBuffer.append(entry.getKey());
                stringBuffer.append('=');
                stringBuffer
                        .append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                stringBuffer.append('&');
            }

            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            httpGet = new HttpGet(URL + stringBuffer.toString());
        }

//        httpGet.setHeader("Authorization", "Bearer " + searchToken);
        httpGet.setHeader("sessionId",sessionId);
        HttpResponse httpResponse = HttpClientHelper.getHttpClient().execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        //		Log.e("############", EntityUtils.toString(httpEntity, HTTP.UTF_8));
        return EntityUtils.toString(httpEntity, HTTP.UTF_8);
    }

    /**
     * 发送get请求
     *
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String doGet1(String url, HashMap<String, Object> maps,
                                String sessionId) throws ClientProtocolException, IOException {
        HttpGet httpGet = null;
        if (maps == null) {
            httpGet = new HttpGet(url);
        } else {
            String URL = url + "?";
            StringBuffer stringBuffer = new StringBuffer();

            for (Map.Entry<String, Object> entry : maps.entrySet()) {
                stringBuffer.append(entry.getKey());
                stringBuffer.append('=');
                stringBuffer.append(entry.getValue());
                stringBuffer.append('&');
            }
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            httpGet = new HttpGet(URL + (stringBuffer.toString().trim()));
        }

//        httpGet.setHeader("Authorization", "Bearer " + searchToken);
        httpGet.setHeader("sessionId",sessionId);
        HttpResponse httpResponse = HttpClientHelper.getHttpClient().execute(
                httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        return EntityUtils.toString(httpEntity, HTTP.UTF_8);
    }

    private static String JSESSIONID = null;

    /**
     * 发送post请求
     *
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String doPost(String url, HashMap<String, String> maps,
                                String sessionId) throws ClientProtocolException, IOException {
        HttpPost httpPost = new HttpPost(url);
        if (null != maps) {
            String json = "";
            if (maps.get("array") != null) {
                json = maps.get("array").toString();
            } else {
                json = new Gson().toJson(maps);
            }
            BaseLog.e("json", json);
            ByteArrayEntity arrayEntity = new ByteArrayEntity(
                    json.getBytes(HTTP.UTF_8));
            httpPost.setEntity(arrayEntity);
        }
        // 第一次一般是还未被赋值，若有值则将SessionId发给服务器
//        if (null != JSESSIONID) {
//            httpPost.setHeader("Cookie", "JSESSIONID=" + JSESSIONID);
//        }
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("charset", "UTF-8");
//        httpPost.setHeader("Authorization", "Bearer " + searchToken);// 查询token

        httpPost.setHeader("sessionId", sessionId);

        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse httpResponse = client.execute(httpPost);

        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            CookieStore mCookieStore = client.getCookieStore();
            List<Cookie> cookies = mCookieStore.getCookies();
            for (int i = 0; i < cookies.size(); i++) {
                // 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
                if ("JSESSIONID".equals(cookies.get(i).getName())) {
                    JSESSIONID = cookies.get(i).getValue();
                    break;
                }

            }
            return EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
        } else {
            return EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
        }

    }

    /***
     * 发送post请求
     * @param url
     * @param maps
     * @param sessionId
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String doPost1(String url, HashMap<String, Object> maps,
                                 String sessionId) throws ClientProtocolException, IOException {
        HttpPost httpPost = new HttpPost(url);
        if (null != maps) {
            String json = "";
            json = new Gson().toJson(maps);
            BaseLog.e("json", json);
            ByteArrayEntity arrayEntity = new ByteArrayEntity(
                    json.getBytes(HTTP.UTF_8));
            httpPost.setEntity(arrayEntity);
        }
        // 第一次一般是还未被赋值，若有值则将SessionId发给服务器
//        if (null != JSESSIONID) {
//            httpPost.setHeader("Cookie", "JSESSIONID=" + JSESSIONID);
//        }
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("charset", "UTF-8");
//        httpPost.setHeader("Authorization", "Bearer " + searchToken);// 查询token

        httpPost.setHeader("sessionId", sessionId);

        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse httpResponse = client.execute(httpPost);

        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            CookieStore mCookieStore = client.getCookieStore();
            List<Cookie> cookies = mCookieStore.getCookies();
            for (int i = 0; i < cookies.size(); i++) {
                // 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
                if ("JSESSIONID".equals(cookies.get(i).getName())) {
                    JSESSIONID = cookies.get(i).getValue();
                    break;
                }

            }
            return EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
        } else {
            return EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
        }

    }

    /***
     * put请求
     * @param url 请求地址
     * @param maps 请求参数
     * @param sessionId 请求头参数
     * @return  响应信息
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String doPut(String url, HashMap<String, String> maps,String sessionId) throws ClientProtocolException, IOException {
        HttpPut httpPut = new HttpPut(url);
        if (null != maps) {
            String json = "";
            json = new Gson().toJson(maps.get("userInfo"));
            BaseLog.e("json", json);
            ByteArrayEntity arrayEntity = new ByteArrayEntity(
                    json.getBytes(HTTP.UTF_8));
            httpPut.setEntity(arrayEntity);
        }
        // 第一次一般是还未被赋值，若有值则将SessionId发给服务器
//        if (null != JSESSIONID) {
//            httpPost.setHeader("Cookie", "JSESSIONID=" + JSESSIONID);
//        }
        httpPut.setHeader("Content-Type", "application/json");
        httpPut.setHeader("charset", "UTF-8");
//        httpPost.setHeader("Authorization", "Bearer " + searchToken);// 查询token

        httpPut.setHeader("sessionId", sessionId);

        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse httpResponse = client.execute(httpPut);

        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            CookieStore mCookieStore = client.getCookieStore();
            List<Cookie> cookies = mCookieStore.getCookies();
            for (int i = 0; i < cookies.size(); i++) {
                // 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
                if ("JSESSIONID".equals(cookies.get(i).getName())) {
                    JSESSIONID = cookies.get(i).getValue();
                    break;
                }

            }
            return EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
        } else {
            return EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
        }
    }

    /***
     * put请求
     * @param url 请求地址
     * @param maps 请求参数
     * @param sessionId 请求头参数
     * @return  响应信息
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String doPut1(String url, HashMap<String, Object> maps,String sessionId) throws ClientProtocolException, IOException {
        HttpPut httpPut = new HttpPut(url);
        if (null != maps) {
            String json = "";
            json = new Gson().toJson(maps.get("userInfo"));
            BaseLog.e("json", json);
            ByteArrayEntity arrayEntity = new ByteArrayEntity(
                    json.getBytes(HTTP.UTF_8));
            httpPut.setEntity(arrayEntity);
        }
        // 第一次一般是还未被赋值，若有值则将SessionId发给服务器
//        if (null != JSESSIONID) {
//            httpPost.setHeader("Cookie", "JSESSIONID=" + JSESSIONID);
//        }
        httpPut.setHeader("Content-Type", "application/json");
        httpPut.setHeader("charset", "UTF-8");
//        httpPost.setHeader("Authorization", "Bearer " + searchToken);// 查询token

        httpPut.setHeader("sessionId", sessionId);

        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse httpResponse = client.execute(httpPut);

        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            CookieStore mCookieStore = client.getCookieStore();
            List<Cookie> cookies = mCookieStore.getCookies();
            for (int i = 0; i < cookies.size(); i++) {
                // 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
                if ("JSESSIONID".equals(cookies.get(i).getName())) {
                    JSESSIONID = cookies.get(i).getValue();
                    break;
                }

            }
            return EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
        } else {
            return EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
        }
    }


    public boolean post(byte[] paramArrayOfByte, String http) {
        ByteArrayEntity arrayEntity = new ByteArrayEntity(paramArrayOfByte);
        arrayEntity.setContentType("application/octet-stream");
        HttpPost httpPost = new HttpPost(http);
        httpPost.setEntity(arrayEntity);
        DefaultHttpClient client = new DefaultHttpClient();
        try {
            int result = client.execute(httpPost).getStatusLine().getStatusCode();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return false;
    }

    public static InputStream doPostInputStream(String url,
                                                List<NameValuePair> params) throws ClientProtocolException,
            IOException {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        // 第一次一般是还未被赋值，若有值则将SessionId发给服务器
        if (null != JSESSIONID) {
            httpPost.setHeader("Cookie", "JSESSIONID=" + JSESSIONID);
        }
        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse httpResponse = client.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            CookieStore mCookieStore = client.getCookieStore();
            List<Cookie> cookies = mCookieStore.getCookies();
            for (int i = 0; i < cookies.size(); i++) {
                // 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
                if ("JSESSIONID".equals(cookies.get(i).getName())) {
                    JSESSIONID = cookies.get(i).getValue();
                    break;
                }

            }
            return httpResponse.getEntity().getContent();
        }
        return null;

    }

}
